// 云函数入口文件
const cloud = require('wx-server-sdk')
const moment = require("moment");

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  moment.locale('zh-cn');
  var m = moment()
  m.set({hour:0,minute:0,second:0,millisecond:0})
  const startWeekDate = moment().week(moment().week()).add(8, 'hours').startOf('week').valueOf();
  console.log(m.weekday(0).format('lll'))
  const endWeekDate = moment().week(moment().week()).add(8, 'hours').endOf('week').valueOf();
  console.log(m.weekday(7).format('lll'))
  console.log(m.week(moment().week()).startOf('week').format('lll'))
  console.log(m.week(moment().week()).endOf('week').format('lll'))
  console.log(m.startOf('month').format('lll'))
  console.log(m.endOf('month').format('lll'))

  const _ = db.command
  let postCards = await db.collection('cards').where({
    _openid: "o4GBQ5AZezqQr2zPn7dIMlRLYYzw",
    type: {
      index:1,
      name:"力量卡"
    },
    systemTime: _.lte(endWeekDate).and(_.gte(startWeekDate)),
  }).get()

  var totalTypePoint = 0
  for (var i = 0; i < postCards.data.length; i++) {
    let pCard = postCards.data[i]
    if (pCard.status == "checked") {
      console.log('checked')
      totalTypePoint += pCard.point
    }
  }
  console.log('postCards', postCards)
  console.log('totalTypePoint', totalTypePoint)
  // card.point = calculatePoint(rules, card, totalTypePoint);
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}